import axios from 'axios'
import { AxiosInstance, AxiosRequestConfig } from 'axios'
import { IResultData } from './interface/interface'

// export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
//     // 请求是否需要显示 loading
//     loading?: boolean;
//     // 是否取消重复请求
//     cancel?: boolean;
//     // 重连配置
//     retryConfig?: {
//         // 重连次数
//         count?: number
//         // 每次请求间隔时间
//         waitTime?: number
//     }
// }

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseUrl: import.meta.env.VITE_APP_BASEURL,
  // 超时时间
  timeout: 5000,
  // 跨域允许携带凭证(cookie)
  witeCredentials: true
}

class RequestHttp {
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config)

    this.service.interceptors.request.use(
      (config) => {
        return config
      },
      (error) => {
        console.log(error)
      }
    )

    this.service.interceptors.request.use(
      (res) => {
        return res.data
      },
      (error) => {
        console.log(error)
      }
    )
  }

  get<T>(url: string, params?: object, _object = {}): Promise<IResultData<T>> {
    return this.service.get(url, { params, ..._object })
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<IResultData<T>> {
    return this.service.post(url, params, _object)
  }
  put<T>(url: string, params?: object, _object = {}): Promise<IResultData<T>> {
    return this.service.put(url, params, _object)
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<IResultData<T>> {
    return this.service.delete(url, { params, ..._object })
  }
  // download(url: string, params?: object, _object = {}): Promise<BlobPart> {
  //   return this.service.post(url, params, { ..._object, responseType: 'blob' })
  // }
}

export default new RequestHttp(config)
